package cc.rengu.redp.bizimpl.upmp.service.impl;

import cc.rengu.jrbdp.protocol.manager.ManagerTaskResult;
import cc.rengu.redp.bizimpl.upmp.bean.BatchTaskBean;
import cc.rengu.redp.bizimpl.upmp.common.BusinessContainer;
import cc.rengu.redp.bizimpl.upmp.domain.UpmpSysParam;
import cc.rengu.redp.bizimpl.upmp.service.OneKeyStartStopService;
import cc.rengu.redp.bizimpl.upmp.service.IUpmpSysParamService;
import cc.rengu.redp.bizimpl.upmp.vo.UpmpUserInfoVO;
import cc.rengu.redp.bizimpl.utils.Common;
import cc.rengu.redp.bizimpl.utils.CommonUtils;
import cc.rengu.redp.bizimpl.utils.RbdpClient;
import cc.rengu.redp.common.domain.RedpResponse;
import cc.rengu.utility.base.TimeUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class OneKeyStartStopServiceImpl implements OneKeyStartStopService {

    public static final Logger logger = LoggerFactory.getLogger(OneKeyStartStopServiceImpl.class);

    @Qualifier("upmpSysParamService")
    @Autowired
    private IUpmpSysParamService upmpSysParamService;
    @Autowired
    private IUpmpSysParamService iUpmpSysParamService;

    @Override
    public RedpResponse setAppInfo(HttpServletRequest request) {

        RedpResponse redpResponse = new RedpResponse();
        String id = request.getParameter("id");
        String status = request.getParameter("status");
        UpmpSysParam upmpSysParam = new UpmpSysParam();

        String dataKey = "0".equals(status)?"stop":"start";
//        UpmpUserInfoVO upmpUserInfoVO = RedpUpmpUtil.getCurrentUser(defaultInstId);
        UpmpUserInfoVO upmpUserInfoVO = CommonUtils.getCurrentUser(upmpSysParamService);
        logger.info("法人行["+upmpUserInfoVO.getInstId()+"]用户["+upmpUserInfoVO.getId()+"]请求执行一键启停["+dataKey+"]操作!");
        if(!upmpUserInfoVO.isAdmin()){
            return redpResponse.failure().message("法人行["+upmpUserInfoVO.getInstId()+"]用户["+upmpUserInfoVO.getId()+"]无权限操作!");
        }
        upmpSysParam = upmpSysParamService.getById(id);
        if(Common.isBlank(upmpSysParam)){
            return redpResponse.failure().message("法人行["+upmpUserInfoVO.getInstId()+"]用户["+upmpUserInfoVO.getId()+"]一键启停请求操作的数据不存在!");
        }
        if(Common.isBlank(upmpSysParam.getRichtextValue())){
            return redpResponse.failure().message("一键启停参数配置错误!");
        }
        Map<String,String> maps = (Map<String, String>) JSON.parse(upmpSysParam.getRichtextValue());
        String command = maps.get(dataKey);
        if(Common.isNotBlank(command)){
            String[] commandSplit = command.split(" ");
            List<String> lcommand = new ArrayList<String>();
            for (int i = 0; i < commandSplit.length; i++) {
                lcommand.add(commandSplit[i]);
            }
            ProcessBuilder processBuilder = new ProcessBuilder(lcommand);
                processBuilder.redirectErrorStream(true);
                InputStream is = null;
                BufferedReader bs = null;
                try {
                    Process p = processBuilder.start();
                    is = p.getInputStream();
                    bs = new BufferedReader(new InputStreamReader(is));

                    p.waitFor();
                    if (p.exitValue() != 0) {
                        //说明命令执行失败
                        logger.error("法人行["+upmpUserInfoVO.getInstId()+"]用户["+upmpUserInfoVO.getId()+"]请求执行一键启停["+dataKey+"]操作失败");
                        return redpResponse.failure().message("法人行["+upmpUserInfoVO.getInstId()+"]用户["+upmpUserInfoVO.getId()+"]请求执行一键启停["+dataKey+"]操作失败");
                    }
                    String line = null;
                    while ((line = bs.readLine()) != null) {
                        logger.info(line);
                    }
                } catch (IOException | InterruptedException e) {
                    logger.error("法人行["+upmpUserInfoVO.getInstId()+"]用户["+upmpUserInfoVO.getId()+"]请求执行一键启停["+dataKey+"]操作出现异常",e);
                    return redpResponse.failure().message("法人行["+upmpUserInfoVO.getInstId()+"]用户["+upmpUserInfoVO.getId()+"]请求执行一键启停["+dataKey+"]操作出现异常:"+e.getMessage());
                }finally {
                    if(Common.isNotBlank(bs)){
                        try {
                            bs.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if(Common.isNotBlank(is)){
                        try {
                            is.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

            }else{
                logger.error("法人行["+upmpUserInfoVO.getInstId()+"]用户["+upmpUserInfoVO.getId()+"]请求执行一键启停["+dataKey+"]操作未获取到指令");
                return redpResponse.failure().message("法人行["+upmpUserInfoVO.getInstId()+"]用户["+upmpUserInfoVO.getId()+"]请求执行一键启停["+dataKey+"]操作未获取到指令");
            }
            return redpResponse.message("操作成功");
    }

    @Override
    public Map<String, Object> getAppInfo() {
        UpmpUserInfoVO upmpUserInfoVO = CommonUtils.getCurrentUser(upmpSysParamService);
        List<UpmpSysParam> list =  iUpmpSysParamService.findChildrenByPrimaryKey(BusinessContainer.ONE_KEY_START_STOP_PRARM,upmpUserInfoVO.getInstId(),null);
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("content", list);
        resultMap.put("page", 1);
        resultMap.put("totalElements", list.size());
        resultMap.put("totalPages", 1);
        return resultMap;
    }
}
